<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>菜品管理</el-breadcrumb-item>
      <el-breadcrumb-item>菜品列表列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- layout布局 -->
      <el-row :gutter="20">
        <!-- 级联选择框 -->
        <el-col :span="3">
          <el-select
            v-model="value"
            clearable
            filterable
            placeholder="请选择菜品分类"
            @change="selectChange"
            @clear="getDishesList"
          >
            <el-option
              v-for="item in classifyList"
              :key="item.classifyId"
              :label="item.classifyname"
              :value="item.classifyId"
            >
            </el-option>
          </el-select>
        </el-col>

        <el-col :span="6">
          <!-- 搜索框 -->
          <el-input
            placeholder="请输入要查找的菜名"
            v-model="queryInfo.query"
            clearable
            @clear="getDishesList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getDishesList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加菜品</el-button
          >
        </el-col>
      </el-row>

      <!-- 表单 -->
      <el-table
        ref="multipleTable"
        :data="dishList"
        tooltip-effect="dark"
        style="width: 100%"
        border
        stripe
      >
        <el-table-column prop="dishId" label="菜品id"> </el-table-column>
        <el-table-column prop="dishList" label="菜品图片">
          <template slot-scope="scope">
            <el-image
              style="width: 100px; height: 100px"
              :src="scope.row.dishpic"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="dishname" label="菜品名称"> </el-table-column>
        <el-table-column prop="dishinfo" label="菜品描述"> </el-table-column>
        <el-table-column prop="dishorder" label="菜品价格"> </el-table-column>
        <el-table-column prop="dishtotal" label="售出份数"> </el-table-column>
        <!-- 这里指定了一个宽度，才能撑下三个按钮 -->
        <el-table-column
          prop="address"
          label="操作"
          show-overflow-tooltip
          width="180px"
        >
          <!-- 这里也是使用了 插槽 -->
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteById(scope.row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 3, 5]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加信息的对话框 -->
    <el-dialog
      title="添加菜品"
      :visible.sync="addDialogVisible"
      @close="addDialogClosed"
    >
      <el-form
        :model="addForm"
        :rules="addFormrules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item label="菜名" prop="dishname">
          <el-input v-model="addForm.dishname"></el-input>
        </el-form-item>
        <el-form-item label="菜品描述" prop="dishinfo">
          <el-input v-model="addForm.dishinfo"></el-input>
        </el-form-item>
        <el-form-item label="菜品价格" prop="dishorder">
          <el-input v-model="addForm.dishorder"></el-input>
        </el-form-item>
        <el-form-item label="菜品分类" prop="classifyid">
          <el-select
            v-model="addForm.classifyid"
            clearable
            filterable
            placeholder="请选择菜品分类"
            @change="selectChange2"
          >
            <el-option
              v-for="item in classifyList"
              :key="item.classifyId"
              :label="item.classifyname"
              :value="item.classifyId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="菜品图片" prop="dishpic">
          <!-- 上传菜品图片 -->
          <el-upload
            class="avatar-uploader"
            action="http://localhost/dishes/uploadPic"
            :show-file-list="false"
            name="dishImg"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addSuccess">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改信息的对话框 -->
    <el-dialog
      title="修改菜品信息"
      :visible.sync="editDialogVisible"
      @close="editDialogClosed"
    >
      <el-form
        label-width="100px"
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
      >
        <el-form-item label="菜名" prop="dishname">
          <el-input v-model="editForm.dishname"></el-input>
        </el-form-item>
        <el-form-item label="菜品描述" prop="dishinfo">
          <el-input v-model="editForm.dishinfo"></el-input>
        </el-form-item>
        <el-form-item label="菜品价格" prop="dishorder">
          <el-input v-model="editForm.dishorder"></el-input>
        </el-form-item>
        <el-form-item label="菜品分类">
          <el-select
            v-model="editForm.classifyid"
            clearable
            filterable
            placeholder="请选择菜品分类"
            @change="selectChange2"
          >
            <el-option
              v-for="item in classifyList"
              :key="item.classifyId"
              :label="item.classifyname"
              :value="item.classifyId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="菜品图片">
          <!-- 上传头像 -->
          <el-upload
            class="avatar-uploader"
            action="http://localhost/dishes/uploadPic"
            :show-file-list="false"
            name="dishImg"
            :on-success="handleAvatarSuccess2"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl2" :src="imageUrl2" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editSuccess">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>



<script>
export default {
  created() {
    this.getClassify();
    this.getDishesList();
  },

  methods: {
    async getDishesList() {
      if (this.value == null) {
        this.classifyId = null;
      }
      console.log(this.queryInfo.query, "我是query");
      const { data: res } = await this.$http.post(
        `/dishes/${this.queryInfo.pagenum}/${this.queryInfo.pagesize}`,
        {
          dishname: this.queryInfo.query,
          classifyid: this.value,
        }
      );
      console.log(res, "我是菜品分页之后拿到的数据");
      this.dishList = res.data.records;
      this.total = res.data.total;
    },
    //获取全部分类
    async getClassify() {
      const { data: res } = await this.$http.get("/classify/all");
      console.log(res, "我是全部分类");
      this.classifyList = res.data;
      this.total = res.data.total;
    },
    async showEditDialog(row) {
      this.editDialogVisible = true;
      const res = await this.$http.get(`/dishes/getDishById/${row.dishId}`);
      console.log(res, "菜品回显");
      this.editForm = res.data.data;
      this.imageUrl2 = res.data.data.dishpic;
    },
    deleteById() {},
    selectChange() {
      console.log(this.value, "我是value");
      this.getDishesList();
    },
    //用于监听添加或者编辑
    selectChange2() {
      console.log(this.addForm.classifyid, "add edit 我是value");
    },
    //监听 pageesize 改变的事件
    handleSizeChange(newSize) {
      console.log(`每页 ${newSize} 条`);
      this.queryInfo.pagesize = newSize;
      this.getDishesList();
    },
    // 监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      console.log(`当前页: ${newPage}`);
      this.queryInfo.pagenum = newPage;
      this.getDishesList();
    },
    //添加图片所用
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      // console.log(this.imageUrl,"图片")
      this.url = res.data;
      console.log(res, ".......");
      console.log(file, "............");
    },
    //添加图片所用
    handleAvatarSuccess2(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      // console.log(this.imageUrl,"图片")
      this.editForm.dishpic = res.data;
      console.log(res, ".......");
      console.log(file, "............");
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    /* 清空添加表单的对话框 监听*/
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
      this.imageUrl=''
    },
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    addSuccess() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (valid) {
          const res = await this.$http.post("/dishes/addDishes", {
            dishname: this.addForm.dishname,
            dishinfo: this.addForm.dishinfo,
            dishpic: this.url,
            dishorder: this.addForm.dishorder,
            classifyid: this.addForm.classifyid,
          });
          console.log(res, "添加菜品之后的返回");
          if (res.data.flag == true) {
            this.addDialogVisible = false;
            this.getDishesList();
            this.$message.success(res.data.msg);
          } else {
            return this.$message.error(res.data.msg);
          }
        }
      });
    },
    editSuccess() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (valid) {
          const { data: res } = await this.$http.put("/dishes/update", {
            dishId: this.editForm.dishId,
            dishname: this.editForm.dishname,
            dishinfo: this.editForm.dishinfo,
            dishorder: this.editForm.dishorder,
            classifyid: this.editForm.classifyid,
            dishpic: this.editForm.dishpic,
          });
          console.log(res, "编辑菜品");
          if (res.flag == true) {
            this.editDialogVisible = false;
            this.$message.success(res.msg);
            this.getDishesList();
          } else {
            return this.$message.error(res.msg);
          }
        }
      });
    },
    //这个用来编辑 回显
    handleAvatarSuccess2(res, file) {
      this.imageUrl2 = URL.createObjectURL(file.raw);
      // console.log(this.imageUrl,"图片")
      this.editForm.dishpic = res.data;
      console.log(res, ".......");
      console.log(file, "............");
    },
  },
  data() {
    let checkInt = (rule, value, callback) => {
      if (Number(value) && value % 1 === 0 && value >= 0) {
        console.log(value);
        callback();
      } else {
        return callback(new Error("请输入正整数！"));
      }
    };
    return {
      dishList: [],
      value: "",
      //用于添加或者编辑菜品分类
      value2: "",
      classifyList: [],
      classifyId: null,
      //获取用户列表的参数对象
      queryInfo: {
        query: "",
        //当前的页数
        pagenum: 1,
        //当前每页显示多少条数据
        pagesize: 3,
      },
      //总数
      total: 0,
      addDialogVisible: false,
      editDialogVisible: false,
      /* 添加菜品 */
      addForm: {
        dishname: "",
        dishinfo: "",
        dishpic: "",
        dishorder: "",
        classifyid: "",
      },
      editForm: {
        dishname: "",
        dishinfo: "",
        dishpic: "",
        dishorder: "",
        classifyid: "",
      },
      url: "",
      //用于添加
      imageUrl: "",
      //用于编辑
      imageUrl2: "",
      addFormrules: {
        dishorder: [
          { required: true, message: "输入价格应为正整数", trigger: "blur" },
          { validator: checkInt },
        ],
      },
      editFormRules: {
        dishorder: [
          { required: true, message: "输入价格应为正整数", trigger: "blur" },
          { validator: checkInt },
        ],
      },
    };
  },
};
</script>

<style scoped>
.el-pagination {
  margin-top: 15px;
}
.el-card {
  margin: 15px 0;
}
.el-table {
  margin-top: 15px;
}
/* 添加头像的样式 */
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>